from flask import Flask,request
from flask_cors import CORS
from config import BaseConfig
import jwt
import datetime
from socketIO import socketIO as socketio

from db import db
from controller.LoginController import loginController,jwt_secret_key
from controller.ModelController import modelController
from controller.TalkController import talkController
from controller.DataController import dataController

from entity.Response import authority

app = Flask(__name__)
app.json.ensure_ascii = False
CORS(app)
app.config.from_object(BaseConfig)
db.init_app(app)
socketio.init_app(app, cors_allowed_origins='*',async_mode='threading') # 用socketio初始化flask的app

app.register_blueprint(loginController, url_prefix='')
app.register_blueprint(modelController, url_prefix='/model')
app.register_blueprint(talkController, url_prefix='/talk')
app.register_blueprint(dataController, url_prefix='/data')

# 路径白名单
allow_paths = ['/login','/register', '/checkToken', '/exportUserInfo',
               '/model/uploadImage','/model/uploadBatchImage','/model/getExportResult','/model/segmentation',
               '/data/getSegmentationCount','/data/getFunctionCount','/data/getActiveUserCount','/data/getWordCloud']

# 全局方法 在请求之前先校验是否含有jwt
@app.before_request
def before_request():
    path = request.path
    if path in allow_paths:
        return None
    # 获取token
    token = request.cookies.get('token')
    if not token:
        token = request.headers.get('token')
    if not token:
        return authority(message='鉴权失败，请先登录！')
    try:
        decoded_payload = jwt.decode(token, jwt_secret_key, algorithms=['HS256'])
    except jwt.ExpiredSignatureError:
        return authority(message='token已过期，请重新登录！')
    except jwt.InvalidTokenError:
        return authority(message='无效token')
    return None

if __name__ == '__main__':
    app.run(debug=True,port=5000)